import os, sys

class Signature( object ):
  def __init__(self, filename, additionalfiles = [] ):
    self.filename = filename
    self.additionalfiles = additionalfiles

  def isvalid(self):
    sign = self.getSignature()   
    
    if os.path.exists( self.filename ):
      with open( self.filename ) as sf:
        
        sign1 = sf.readlines()[-1].strip()
        return sign1 == sign
    return False

  def resign(self, targetfile = None):
    if not targetfile:
      targetfile = self.filename
    with open( targetfile, "w" ) as sf:
      sf.write( self.getSelfInfo() + "\n" ) 
      sf.write( self.getSignature() + "\n")

  def getSignature(self):
    import inspect
    import hashlib
    stack = inspect.stack()
    uniquefiles = []
    ufset = set( [el[1] for el in stack ] )
    ufset.add(inspect.getsourcefile(inspect.getmodule(self)))
    #add additional files to check ( given in constructor )
    for addfile in self.additionalfiles:
      ufset.add(addfile) 
    uniquefiles += ufset
    uniquefiles.sort()

    m = hashlib.sha256()
    for f in uniquefiles:
      if not os.path.isabs(f):
        f = os.path.join(sys.path[0], f)
      if os.path.isfile(f):
        try:
          with open(f) as openfile:
            src = openfile.read()
            m.update(src)
        except:
          print "Could not open: ", f
    return m.hexdigest()

  def getSelfInfo(self):
    return "Buildext (http://buildext.googlecode.com)"

